<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="equipmentNumber">
        <el-input
          v-model="queryParams.equipmentNumber"
          placeholder="请输入设备编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="终端类型" prop="terminalType">
        <el-select v-model="queryParams.terminalType" placeholder="请选择终端类型" clearable size="small">
          <el-option
            v-for="dict in terminalTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="当前状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择当前状态" clearable size="small">
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basicInformation:terminal:add']"
        >新增
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['basicInformation:terminal:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basicInformation:terminal:remove']"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basicInformation:terminal:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="terminalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主建id" align="center" prop="id" v-if="false"/>
      <el-table-column label="设备名称" align="center" prop="equipmentName"/>
      <el-table-column label="设备编号" align="center" prop="equipmentNumber"/>
      <el-table-column label="终端标识" align="center" prop="identification"/>
      <el-table-column label="设备品牌" align="center" prop="equipmentBrand"/>
      <el-table-column label="SIM卡" align="center" prop="simCard"/>
      <el-table-column label="终端类型" align="center" prop="terminalType" :formatter="terminalTypeFormat"/>
      <el-table-column label="当前状态" align="center" prop="state" :formatter="stateFormat"/>
      <el-table-column label="当天上线次数" align="center" prop="dayNum"/>
      <el-table-column label="当天之前总上线次数" align="center" prop="befDayNum"/>
      <el-table-column label="当天里程数(米)" align="center" prop="dayMileage"/>
      <el-table-column label="当天之前总里程数(米)" align="center" prop="befDayMileage"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basicInformation:terminal:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basicInformation:terminal:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改终端注册对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入设备名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="equipmentNumber">
              <el-input v-model="form.equipmentNumber" placeholder="请输入设备编号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="终端标识" prop="identification">
              <el-input v-model="form.identification" placeholder="请输入终端标识"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备品牌" prop="equipmentBrand">
              <el-input v-model="form.equipmentBrand" placeholder="请输入设备品牌"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="SIM卡" prop="simCard">
              <el-input v-model="form.simCard" placeholder="请输入SIM卡"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终端类型" prop="terminalType">
              <el-select v-model="form.terminalType" placeholder="请选择终端类型">
                <el-option
                  v-for="dict in terminalTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="当前状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择当前状态">
                <el-option
                  v-for="dict in stateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="parentId">
              <treeselect v-model="form.areaId" :options="districtOptions" :show-count="true" placeholder="请选择区域"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>








      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listTerminal,
    getTerminal,
    delTerminal,
    addTerminal,
    updateTerminal,
    exportTerminal,
    synchronizationTerminal
  } from '@/api/basicInformation/terminal'
  import { rySynchronizationTerminalMileage } from '../../../api/basicInformation/trajectory'

  import {treeselectArea} from '@/api/basicInformation/area'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: 'Terminal',
    components: {
      Treeselect
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 区域树选项
        districtOptions: undefined,
        // 终端注册表格数据
        terminalList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 终端类型字典
        terminalTypeOptions: [],
        // 当前状态字典
        stateOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          equipmentName: undefined,
          equipmentNumber: undefined,
          terminalType: undefined,
          state: undefined,
          orderByColumn: 'createTime',
          isAsc: 'desc'
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          terminalType: [
            { required: true, message: '终端类型不能为空', trigger: 'change' }
          ],
          equipmentName: [
            { required: true, message: '终端名称不能为空', trigger: 'blur' }
          ],
          equipmentNumber: [
            { required: true, message: '终端编码不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.getList()
      this.getTreeselect();
      this.getDicts('terminal_type').then(response => {
        this.terminalTypeOptions = response.data
      })
      this.getDicts('terminal_state').then(response => {
        this.stateOptions = response.data
      })
    },
    methods: {
      getTreeselect() {
        treeselectArea().then(response => {
          this.districtOptions = response.data
        })
      },
      /** 查询终端注册列表 */
      getList() {
        this.loading = true
        listTerminal(this.queryParams).then(response => {
          this.terminalList = response.rows
          this.total = response.total
          // this.getDayMileageFormat()
          this.loading = false
        })
      },
      // 终端类型字典翻译
      terminalTypeFormat(row, column) {
        return this.selectDictLabel(this.terminalTypeOptions, row.terminalType)
      },
      // 当前状态字典翻译
      stateFormat(row, column) {
        return this.selectDictLabel(this.stateOptions, row.state)
      },
      getDayMileageFormat() {
        this.terminalList.forEach(item => {
          rySynchronizationTerminalMileage(item.id).then(rs => {
            if (rs.code === 200) {
              item.dayMileage = rs.data
            } else {
              item.dayMileage = 0
            }
          })
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          equipmentName: undefined,
          equipmentNumber: undefined,
          identification: undefined,
          equipmentBrand: undefined,
          simCard: undefined,
          terminalObjectId: undefined,
          terminalType: undefined,
          state: undefined,
          remark: undefined,
          dayNum: undefined,
          befDayNum: undefined,
          delFlag: undefined,
          createById: undefined,
          createBy: undefined,
          createTime: undefined,
          updateById: undefined,
          updateBy: undefined,
          updateTime: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.names = selection.map(item => item.equipmentName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加终端注册'
      },
      handleSynchronizationTerminal() {
        synchronizationTerminal()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        getTerminal(id).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改终端注册'
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateTerminal(this.form).then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addTerminal(this.form).then(response => {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        const names = row.equipmentName || this.names
        this.$confirm('是否确认删除设备名称为"' + names + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delTerminal(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有终端注册数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportTerminal(queryParams)
        }).then(response => {
          this.download(response.msg)
        })
      }
    }
  }
</script>
